#人脸检测小案例 opencv+MTCNN
import matplotlib.pyplot as plt
from mtcnn import MTCNN
import cv2
import os
from matplotlib.patches import Rectangle
from matplotlib.patches import Circle

#定义函数:绘制人脸检测框
def draw_boxes(img_path, faces):
	
	# 加载图片
	img = plt.imread(img_path)

	# 显示图片
	plt.imshow(img)


	# 创建子图，绘制检测框
	ax = plt.gca()

	# 绘制框
	for face in faces:
		# 获取坐标值，x, y, w, h
		x, y, w, h = face['box']
		# 矩形框
		rect = Rectangle((x, y), w, h, fill=False, color='blue')
		# 绘制
		ax.add_patch(rect)

		# 绘制人脸的五个关键点
		for k, v in face['keypoints'].items():
			# 绘制圆形点, v：坐标值，radius：圆形半径
			point = Circle(v, radius=2, color='red')
			# 绘制
			ax.add_patch(point)

	# 显示
	plt.show()


os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
imgpath="301.jpg"
img = cv2.cvtColor(cv2.imread(imgpath), cv2.COLOR_BGR2RGB)
detector = MTCNN()
faces=detector.detect_faces(img)

# 输出检测信息
for face in faces:
	print(face)


# 调用函数，传递图片所在的路径，以及人脸检测框信息

draw_boxes(imgpath, faces)



